<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, updateUserStatus, getUserDetail, deleteUser, resetUserPassword } from '@/api/user'
import request from '@/utils/request'

// 用户列表数据
const userList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchForm = reactive({
  keyword: ''
})

// 用户表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  nickname: '',
  phone: '',
  status: 1
})
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}
const userFormRef = ref(null)

// 用户详情对话框
const detailDialogVisible = ref(false)
const currentUser = ref(null)

// 加载用户列表
const loadUserList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    }
    
    const res = await getUserList(params)
    if (res.code === 200) {
      userList.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错', error)
    ElMessage.error('获取用户列表失败，请稍后重试')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadUserList()
}

// 处理重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.currentPage = 1
  loadUserList()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadUserList()
}

// 查看用户详情
const handleViewDetail = async (row) => {
  try {
    const res = await getUserDetail(row.id)
    if (res.code === 200) {
      currentUser.value = res.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情出错', error)
    ElMessage.error('获取用户详情失败，请稍后重试')
  }
}

// 重置密码
const handleResetPassword = (row) => {
  ElMessageBox.confirm(
    '确认要重置该用户的密码吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await resetUserPassword(row.id)
        if (res.code === 200) {
          ElMessage.success(`密码重置成功，新密码: ${res.data}`)
        } else {
          ElMessage.error(res.message || '密码重置失败')
        }
      } catch (error) {
        console.error('密码重置出错', error)
        ElMessage.error('密码重置失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 处理用户状态更新
const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确认要${statusText}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await updateUserStatus(row.id, newStatus)
        if (res.code === 200) {
          ElMessage.success(`${statusText}成功`)
          loadUserList()
        } else {
          ElMessage.error(res.message || `${statusText}失败`)
        }
      } catch (error) {
        console.error('更新用户状态出错', error)
        ElMessage.error(`${statusText}失败，请稍后重试`)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 格式化用户状态
const formatStatus = (status) => {
  return status === 1 ? '正常' : '禁用'
}

// 打开新增用户对话框
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  userForm.id = null
  userForm.username = ''
  userForm.password = ''
  userForm.nickname = ''
  userForm.phone = ''
  userForm.status = 1
  dialogVisible.value = true
}

// 打开编辑用户对话框
const handleEdit = async (row) => {
  try {
    const res = await getUserDetail(row.id)
    if (res.code === 200) {
      dialogTitle.value = '编辑用户'
      userForm.id = res.data.id
      userForm.username = res.data.username
      userForm.nickname = res.data.nickname
      userForm.phone = res.data.phone
      userForm.status = res.data.status
      dialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情出错', error)
    ElMessage.error('获取用户详情失败，请稍后重试')
  }
}

// 处理删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await deleteUser(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadUserList()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除用户出错', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 提交表单
const submitForm = async () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const method = userForm.id ? 'put' : 'post'
        const url = '/user'
        
        // 创建数据对象的副本，避免修改原始表单
        const formData = { ...userForm }
        
        // 如果是编辑模式，并且密码为空，则删除密码字段
        if (userForm.id && (!formData.password || formData.password === '')) {
          delete formData.password
        }
        
        const res = await request({
          url,
          method,
          data: formData
        })
        
        if (res.code === 200) {
          ElMessage.success(userForm.id ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          loadUserList()
        } else {
          // 显示具体的错误信息
          ElMessage.error(res.message || (userForm.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交用户表单出错', error)
        // 尝试提取API错误信息
        const errorMsg = error.response?.data?.message || '操作失败，请稍后重试'
        ElMessage.error(errorMsg)
      }
    }
  })
}

onMounted(() => {
  loadUserList()
})
</script>

<template>
  <div class="user-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="用户名/昵称/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增用户</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="() => handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              type="info"
              size="small"
              @click="handleViewDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>

            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="!!userForm.id"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.id">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="userForm.nickname"
            placeholder="请输入昵称"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ currentUser?.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentUser?.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentUser?.nickname }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser?.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser?.status === 1 ? 'success' : 'danger'">
            {{ currentUser?.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentUser?.createTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 